package com.pvdnc.dxhook;

import android.util.Log;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Objects;

public class MethodUtils {
    private static final String TAG=MethodUtils.class.getSimpleName();
    public static void ensureInitialized(Method method){
        Class<?> declClass= method.getDeclaringClass();
        //初始化构造器
        Constructor[] constructors=declClass.getConstructors();
        for (Constructor constructor:constructors){
            performInvalidCall(constructor);
        }
        //解析static方法
        if(!Modifier.isStatic(method.getModifiers())){
            return;
        }
        performInvalidCall(method);
    }

    private static void performInvalidCall(Method method){
        Class<?>[] paramTypes= method.getParameterTypes();
        int fakeParamLength=paramTypes.length+1;
        Object[] fakeParamArray=new Object[fakeParamLength];
        try {
            method.invoke(null,fakeParamArray);
            throw new IllegalStateException("fail to make a invalid call for method:\n\t"+method);
        } catch (IllegalAccessException |IllegalArgumentException| InvocationTargetException e) {
            Log.d(TAG,"static method:\n\t"+method+" has been initialized");
            //e.printStackTrace();
        }
    }

    private static void performInvalidCall(Constructor constructor){
        Class<?>[] paramTypes= constructor.getParameterTypes();
        int fakeParamLength=paramTypes.length+1;
        Object[] fakeParamArray=new Object[fakeParamLength];
        try {
            constructor.newInstance(null,fakeParamArray);
            throw new IllegalStateException("fail to make a invalid call for constructor:\n\t"+constructor);
        } catch (IllegalAccessException |IllegalArgumentException| InvocationTargetException|InstantiationException e) {
            Log.d(TAG,"constructor:\n\t"+constructor+" has been initialized");
            //e.printStackTrace();
        }
    }
}
